/*
 *    Copyright 2021 Institute of Software Chinese Academy of Sciences, ISRC

 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */
import http from '@ohos.net.http';
import router from '@system.router';
import bundle from '@ohos.bundle'
import util from '@ohos.util'
import prompt from '@system.prompt'
export default {
    data: {
        endIndex: 0,
        appList: [],
        xtoken: "",
        xsession: "",
        xaccessToken: "",
    },
    onInit() {
        this.get_temporary_xtoken();
    },
    onGetAppList() {
        // 每一个httpRequest对应一个http请求任务，不可复用
        let httpRequest = http.createHttp();
        httpRequest.on('headersReceive', (data) => {
            console.info('header: ' + data.header);
        });
        httpRequest.request(
            // 填写http请求的url地址，可以带参数也可以不带参数。URL地址需要开发者自定义。GET请求的参数可以在extraData中指定
            this.$app.$def.data.appstoreIP + '/mec/appstore/v2/packages/pullable?appName=&limit=100&offset=0&sortType=desc&sortItem=createTime',
            {
                method: 'GET', // 可选，默认为“GET”
                // 开发者根据自身业务需要添加header字段
                header: {
                    'Content-Type': 'application/json'
                },
                // 当使用POST请求时此字段用于传递内容
                extraData: {
                    //"data": "data to send",
                },
                connectTimeout: 60000, // 可选，默认为60s
                readTimeout: 60000, // 可选，默认为60s
            },(err, data) => {
            if (!err) {
                // data.result为http响应内容，可根据业务需要进行解析
                console.info('myapp onInit Result:' + data.result);
                console.info('myapp code:' + data.responseCode);
                // data.header为http响应头，可根据业务需要进行解析
                //console.info('myapp header:' + data.header);
                //console.info('myapp cookies:' + data.cookies); // 8+
                this.appList = JSON.parse(data.result);
                this.$app.$def.data.appList = JSON.parse(data.result);
                for (var i = 0; i < this.appList.length; i++) {
                    this.onDownloadIcon(this.appList[i].packageId, i);
                    this.onAppScore(this.appList[i].appId, i);
                    this.onAppComment(this.appList[i].appId, i);
                }
                console.info("myapp this.applist length:" + this.appList.length);
            } else {
                console.info('myapp error:' + err);
                // 当该请求使用完毕时，调用destroy方法主动销毁。
                httpRequest.destroy();
            }
        }
        );
    },
    onUser() {
        console.info("myapp page to user" + this.$app.$def.data.name);
        if (this.$app.$def.data.name == "guest") {
            router.push({
                uri: "pages/login/login",
                params: {
                    lastPage: "pages/index/index"
                }
            });
        } else {
            router.push({
                uri: "pages/userstate/userstate",
            });
        }
    },
    onDesc(appItem) {
        router.push({
            uri: "pages/description/description",
            params: {
                appItem: appItem,
            }
        })
    },
    onIcon(packageId, pic, i) {
        console.info("myapp onIcon packageId:" + packageId);
        var url = pic;
        var idstr = "canvas" + i;
        const el = this.$element(idstr);
        var ctx =el.getContext('2d');
        ctx.clearRect(0, 0, 60, 60);
        var img = new Image();
        img.src = url;
        img.onload = function() {
            console.log('myapp begin to draw image');
            ctx.drawImage(img, 0, 0, 60, 60);
            url = null;
        };
        img.onerror = function() {
            console.log('myapp onload fail');
        };
    },
    onDownloadIcon(packageId, i) {
        console.info("myapp onDownloadIcon");
        // 每一个httpRequest对应一个http请求任务，不可复用
        let httpRequest = http.createHttp();
        // 用于订阅http响应头，此接口会比request请求先返回。可以根据业务需要订阅此消息
        // 从API 8开始，使用on('headersReceive', Callback)替代on('headerReceive', AsyncCallback)。 8+
        httpRequest.on('headersReceive', (data) => {
            console.info('header: ' + data.header);
        });
        let url = this.$app.$def.data.appstoreIP + "/mec/appstore/v1/packages/" + packageId + "/action/download-icon"
        httpRequest.request(
        // 填写http请求的url地址，可以带参数也可以不带参数。URL地址需要开发者自定义。GET请求的参数可以在extraData中指定
            url,
            {
                method: 'GET', // 可选，默认为“GET”
                // 开发者根据自身业务需要添加header字段
                header: {
                    'Content-Type': 'application/json'
                },
                // 当使用POST请求时此字段用于传递内容

                extraData: {
                    //"data": "data to send",
                },
                connectTimeout: 60000, // 可选，默认为60s
                readTimeout: 60000, // 可选，默认为60s
            },(err, data) => {
            if (!err) {
                // data.result为http响应内容，可根据业务需要进行解析
                //console.info('myapp Result:' + data.result);
                console.info('myapp request icon code:' + data.responseCode);
                // data.header为http响应头，可根据业务需要进行解析
                var lresult = new Uint8Array(data.result);
                var that = new util.Base64();
                var finresult = that.encodeToStringSync(lresult);
                var pic = "data:image/jpeg;base64," + finresult;
                this.appList[i].deployMode = pic;
                this.$app.$def.data.appList[i].deployMode = pic;
            } else {
                console.info('myapp error:' + err);
                // 当该请求使用完毕时，调用destroy方法主动销毁。
                httpRequest.destroy();
            }
        }
        );
    },
    get_temporary_xtoken() {
        let url  = this.$app.$def.data.usermgmtIP + '/v1/identity/verifycode-image?t=' + Math.random()
        let httpRequest = http.createHttp();
        httpRequest.on('napi_headersReceive', (data) => {
        });
        httpRequest.request(
            url,
            {
                method: 'GET', // 可选，默认为“GET”
                header: {
                    'Content-Type': 'image/jpeg',
                },
                connectTimeout: 60000, // 可选，默认为60s
                readTimeout: 60000, // 可选，默认为60s
            },(err, data) => {
            if (!err) {
                console.info('myapp:' + data.result);
                console.info('myapp:' + JSON.stringify(data.cookies));
                var start_token = data.cookies.indexOf('XSRF-TOKEN'); // XSRF-TOKEN的开始位置

                console.info('myapp1 xtoken:' + data.cookies.substring(data.cookies.length-137, data.cookies.length-94));
                console.info('myapp2 xtoken:' + data.cookies.substring(start_token + 11, start_token + 47));
                this.xtoken = data.cookies.substring(start_token + 11, start_token + 47);
                this.xsession = data.cookies.substring(data.cookies.length-32);
                console.info('myapp:' + this.xtoken);
                console.info('myapp:' + this.xsession);
                this.get_temporary_access_token();
            } else {
                console.info('myapp:' + err);
                prompt.showToast({
                    message: "该设备未连接网络",
                    duration: 10000,
                })
                // 当该请求使用完毕时，调用destroy方法主动销毁。
                httpRequest.destroy();
            }
        }
        );
    },
    
    get_temporary_access_token() {
        let url = this.$app.$def.data.usermgmtIP + '/v1/accesstoken';
        let httpRequest = http.createHttp();
        httpRequest.on('headersReceive', (data) => {
        });
        let session_value = 'AUTHSERVERSESSIONID=' + this.xsession + ';';
        let cookie_value = session_value + 'XSRF-TOKEN=' + this.xtoken + ';';
        console.info("myapp get_temporary_access_token cookie:" + cookie_value);
        httpRequest.request(
            url,
            {
                method: 'POST', // 可选，默认为“GET”
                header: {
                    'Content-Type': 'application/json',
                    'Cookie': cookie_value,
                    'Connection': 'keep-alive',
                    'Accept-Encoding': 'gzip, deflate, br',
                    'Accept': '*/*',
                    'X-XSRF-TOKEN': this.xtoken
                },
                extraData:
                {
                    "userFlag": 'guest',
                    "password": 'guest'
                },
                connectTimeout: 60000, // 可选，默认为60s
                readTimeout: 60000, // 可选，默认为60s
            },(err, data) => {
            if (!err) {
                console.info('myapp get_temporary_access_token code:' + data.responseCode);
                console.info('myapp get_temporary_access_token cookies:' + data.cookies);
                this.xaccessToken = JSON.parse(data.result).accessToken;
                console.info("myapp xaccesstoken:" + this.xaccessToken);
                httpRequest.destroy();
                this.onGetAppList();
            } else {
                console.info('myapp get_temporary_access_token error:' + err);
                httpRequest.destroy();
            }
        }
        );

    },
    onAppScore(appId, i) {
        console.info("myapp onDownloadIcon");
        // 每一个httpRequest对应一个http请求任务，不可复用
        let httpRequest = http.createHttp();
        // 用于订阅http响应头，此接口会比request请求先返回。可以根据业务需要订阅此消息
        // 从API 8开始，使用on('headersReceive', Callback)替代on('headerReceive', AsyncCallback)。 8+
        httpRequest.on('headersReceive', (data) => {
            console.info('header: ' + data.header);
        });
        let url = this.$app.$def.data.appstoreIP + "/mec/appstore/v1/apps/" + appId
        httpRequest.request(
            // 填写http请求的url地址，可以带参数也可以不带参数。URL地址需要开发者自定义。GET请求的参数可以在extraData中指定
            url,
            {
                method: 'GET', // 可选，默认为“GET”
                // 开发者根据自身业务需要添加header字段
                header: {
                    'Content-Type': 'application/json',
                    'accesstoken': this.xaccessToken
                },
                // 当使用POST请求时此字段用于传递内容

                extraData: {
                    //"data": "data to send",
                },
                connectTimeout: 60000, // 可选，默认为60s
                readTimeout: 60000, // 可选，默认为60s
            },(err, data) => {
            if (!err) {
                // data.header为http响应头，可根据业务需要进行解析
                this.appList[i].atpTestTaskId = JSON.parse(data.result).score;
                this.appList[i].targetPlatform = JSON.parse(data.result).downloadCount;
                this.$app.$def.data.appList[i].atpTestTaskId = JSON.parse(data.result).score;
                this.$app.$def.data.appList[i].targetPlatform = JSON.parse(data.result).downloadCount;
            } else {
                console.info('myapp error:' + err);
                // 当该请求使用完毕时，调用destroy方法主动销毁。
                httpRequest.destroy();
            }
        }
        );
    },
    onAppComment(appId, i) {
        console.info("myapp onDownloadIcon");
        // 每一个httpRequest对应一个http请求任务，不可复用
        let httpRequest = http.createHttp();
        // 用于订阅http响应头，此接口会比request请求先返回。可以根据业务需要订阅此消息
        // 从API 8开始，使用on('headersReceive', Callback)替代on('headerReceive', AsyncCallback)。 8+
        httpRequest.on('headersReceive', (data) => {
            console.info('header: ' + data.header);
        });
        let url = this.$app.$def.data.appstoreIP + "/mec/appstore/v2/apps/" + appId + "/comments?limit=100&offset=0";
        httpRequest.request(
            // 填写http请求的url地址，可以带参数也可以不带参数。URL地址需要开发者自定义。GET请求的参数可以在extraData中指定
            url,
            {
                method: 'GET', // 可选，默认为“GET”
                // 开发者根据自身业务需要添加header字段
                header: {
                    'Content-Type': 'application/json',
                    'accesstoken': this.xaccessToken
                },
                // 当使用POST请求时此字段用于传递内容

                extraData: {
                    //"data": "data to send",
                },
                connectTimeout: 60000, // 可选，默认为60s
                readTimeout: 60000, // 可选，默认为60s
            },(err, data) => {
            if (!err) {
                // data.result为http响应内容，可根据业务需要进行解析
                this.appList[i].sourcePlatform = JSON.parse(data.result).total;
                this.$app.$def.data.appList[i].sourcePlatform = JSON.parse(data.result).total;
            } else {
                console.info('myapp error:' + err);
                // 当该请求使用完毕时，调用destroy方法主动销毁。
                httpRequest.destroy();
            }
        }
        );
    }


}
